package com.lanou.liuqixin.datebasedemo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.lanou.liuqixin.datebasedemo.R;
import com.lanou.liuqixin.datebasedemo.adapter.SpinnerSeriesAdapter;
import com.lanou.liuqixin.datebasedemo.entity.BrandEntity;
import com.lanou.liuqixin.datebasedemo.entity.CarDetailEntity;
import com.lanou.liuqixin.datebasedemo.entity.SeriesEntity;
import com.lanou.liuqixin.datebasedemo.retrofit.HttpManger;

import java.util.List;

import db.CarEntity;
import db.DatabaseTool;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by dllo on 17/4/26.
 */

public class RetroitActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private Spinner brandSp, seriesSp, typeSp;
    private SpinnerSeriesAdapter mSpinnerBrandAdapter, mSpinnerSeriesAdapter, mSpinnerTypeAdapter;
    private int brandId, seriesId, chexiId;
    private TextView contentTv, contentTwoTv;
    private EditText nameEt;
    private ImageView saveIv, backIv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retriot);
        contentTv = (TextView) findViewById(R.id.content_tv);
        contentTwoTv = (TextView) findViewById(R.id.content2_tv);
        nameEt = (EditText) findViewById(R.id.cheming_et);
        saveIv = (ImageView) findViewById(R.id.save_iv);
        backIv = (ImageView) findViewById(R.id.bear_iv);
        //初始化spinner
        brandSp = (Spinner) findViewById(R.id.pingpai_sp);
        seriesSp = (Spinner) findViewById(R.id.chexi_sp);
        typeSp = (Spinner) findViewById(R.id.chexing_sp);

        //初始化适配器
        mSpinnerBrandAdapter = new SpinnerSeriesAdapter(RetroitActivity.this);
        mSpinnerSeriesAdapter = new SpinnerSeriesAdapter(RetroitActivity.this);
        mSpinnerTypeAdapter = new SpinnerSeriesAdapter(RetroitActivity.this);

        brandSp.setOnItemSelectedListener(this);
        seriesSp.setOnItemSelectedListener(this);
        typeSp.setOnItemSelectedListener(this);


        //调用网络请求方法 请求汽车品牌
        HttpManger.getInstance().getBearApi().getBrands().flatMap(new Function<BrandEntity, ObservableSource<SeriesEntity>>() {
            @Override
            public ObservableSource<SeriesEntity> apply(@NonNull BrandEntity brandEntity) throws Exception {
                List<String> names = brandEntity.getNames();
                List<Integer> indxes = brandEntity.getIdxes();

                return Observable.zip(Observable.fromIterable(indxes), Observable.fromIterable(names), new BiFunction<Integer, String, SeriesEntity>() {
                    @Override
                    public SeriesEntity apply(@NonNull Integer integer, @NonNull String s) throws Exception {
                        SeriesEntity seriesEntity = new SeriesEntity();
                        seriesEntity.setIndex(integer);
                        seriesEntity.setName(s);
                        return seriesEntity;
                    }
                });
            }
        }).toList().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<SeriesEntity>>() {
            @Override
            public void accept(@NonNull List<SeriesEntity> seriesEntities) throws Exception {
                //请求成功将结果绑定适配器
                mSpinnerBrandAdapter.addAll(seriesEntities);
                brandSp.setAdapter(mSpinnerBrandAdapter);

            }
        });


//        //设置品牌栏目的点击事件
//        brandSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                brandId = (int) id;
//                if (brandId == 0) {
//                    mSpinnerBrandAdapter.setColor(true);
//                    mSpinnerSeriesAdapter.setColor(false);
//                    typeSp.setEnabled(false);
//                    return;
//                } else {
//                    typeSp.setEnabled(true);
//                }
//                initSeries();
//
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });
//        //车系的点击事件
//        seriesSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                seriesId = (int) id;
//                mSpinnerTypeAdapter.clear();
//                if (seriesId == 0) {
//                    mSpinnerSeriesAdapter.setColor(true);
//                    mSpinnerTypeAdapter.setColor(false);
//                    typeSp.setEnabled(false);
//                    return;
//                } else {
//                    typeSp.setEnabled(true);
//                }
//                initType();
//
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });
//        //车型的点击事件
//        typeSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                chexiId = (int) id;
//                if (chexiId == 0) {
//                    contentTv.setVisibility(View.INVISIBLE);
//                    contentTwoTv.setVisibility(View.INVISIBLE);
//                } else {
//                    contentTv.setVisibility(View.VISIBLE);
//                    contentTwoTv.setVisibility(View.VISIBLE);
//                }
//                initDetail();
//
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });


        //汽车id保存点击事件
        saveIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(RetroitActivity.this, "信息已经保存", Toast.LENGTH_SHORT).show();
                CarEntity carEntity = new CarEntity(0);
                carEntity.setName(nameEt.getText().toString());
                carEntity.setModel(chexiId);
                carEntity.setSelected(1);
                //保存至数据库中
                DatabaseTool.getInstance().addCar(carEntity);
                Intent intent = new Intent(RetroitActivity.this, MainActivity.class);
                startActivity(intent);

            }
        });
        backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RetroitActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });


    }

    //调用网络数据
    //车系
    private void initSeries() {
        HttpManger.getInstance().getBearApi().getCarSeries(brandId).flatMap(new Function<BrandEntity, ObservableSource<SeriesEntity>>() {
            @Override
            public ObservableSource<SeriesEntity> apply(@NonNull BrandEntity brandEntity) throws Exception {
                List<Integer> index = brandEntity.getIdxes();
                List<String> name = brandEntity.getNames();
                return Observable.zip(Observable.fromIterable(index), Observable.fromIterable(name), new BiFunction<Integer, String, SeriesEntity>() {
                    @Override
                    public SeriesEntity apply(@NonNull Integer integer, @NonNull String s) throws Exception {
                        SeriesEntity seriesEntity = new SeriesEntity();
                        seriesEntity.setIndex(integer);
                        seriesEntity.setName(s);
                        return seriesEntity;
                    }
                });
            }
        }).toList().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<SeriesEntity>>() {
            @Override
            public void accept(@NonNull List<SeriesEntity> list) throws Exception {
                mSpinnerSeriesAdapter.addAll(list);
                seriesSp.setAdapter(mSpinnerSeriesAdapter);
            }
        });
    }

    //调用网络数据
    //车型
    private void initType() {
        HttpManger.getInstance().getBearApi().getCarType(brandId, seriesId).flatMap(new Function<BrandEntity, ObservableSource<SeriesEntity>>() {
            @Override
            public ObservableSource<SeriesEntity> apply(@NonNull BrandEntity brandEntity) throws Exception {
                List<Integer> index = brandEntity.getIdxes();
                List<String> name = brandEntity.getNames();
                return Observable.zip(Observable.fromIterable(index), Observable.fromIterable(name), new BiFunction<Integer, String, SeriesEntity>() {
                    @Override
                    public SeriesEntity apply(@NonNull Integer integer, @NonNull String s) throws Exception {
                        SeriesEntity seriesEntity = new SeriesEntity();
                        seriesEntity.setIndex(integer);
                        seriesEntity.setName(s);
                        return seriesEntity;
                    }
                });
            }
        }).toList().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<SeriesEntity>>() {
            @Override
            public void accept(@NonNull List<SeriesEntity> list) throws Exception {
                mSpinnerTypeAdapter.addAll(list);
                typeSp.setAdapter(mSpinnerTypeAdapter);

            }
        });
    }

    private void initDetail() {
        HttpManger.getInstance().getBearApi().getCarDetail(chexiId).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<CarDetailEntity>() {
            @Override
            public void accept(@NonNull CarDetailEntity carDetailEntity) throws Exception {
                if (carDetailEntity.getEngine() == null || carDetailEntity.getEngine().equals("")) {
                    contentTv.setText("无");
                    contentTwoTv.setText("无");
                } else {
                    contentTv.setText(carDetailEntity.getEngine().trim());
                    contentTwoTv.setText(carDetailEntity.getEngine().trim());
                    Toast.makeText(RetroitActivity.this, "完整车辆信息", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        LinearLayout details = (LinearLayout) findViewById(R.id.car_details_ly);
        switch (parent.getId()) {
            case R.id.pingpai_sp:
                brandId = (int) id;
                mSpinnerSeriesAdapter.clear();
                if (brandId == 0) {
                    mSpinnerSeriesAdapter.setColor(false);
                    seriesSp.setEnabled(false);
                    return;
                } else {
                    seriesSp.setEnabled(true);
                }
                initSeries();
                break;
            case R.id.chexi_sp:
                seriesId = (int) id;
                mSpinnerTypeAdapter.clear();
                if (seriesId == 0) {
                    mSpinnerSeriesAdapter.setColor(false);
                    typeSp.setEnabled(false);
                    return;
                } else {
                    typeSp.setEnabled(true);
                }
                initType();
                break;
            case R.id.chexing_sp:
                chexiId = (int) id;
                if (seriesId == 0) {
                    details.setVisibility(View.INVISIBLE);
                    return;
                } else {
                    details.setVisibility(View.VISIBLE);
                    initDetail();
                    break;
                }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}
